<template>
  <!-- 新增 -->
  <div>
    <el-dialog
      width="500px"
      custom-class="customWidth"
      center
      :before-close="closeDialog"
      title="新增账户"
      :close-on-click-modal="false"
      :visible.sync="addDialogFormVisible"
    >
      <el-form
        :model="adddataForm"
        :rules="adddataRule"
        ref="adddataForm"
        @keyup.enter.native="adddataFormSubmit()"
        label-width="100px"
      >
        <el-form-item label="账户类型" prop="userType">
          <el-col :span="15">
            <el-select
              v-model="adddataForm.userType"
              placeholder="请选择"
              style="width:100%"
              size="mini"
              @change="currentSel"
            >
              <el-option
                v-for="item in userTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-col :span="15">
            <el-input v-model="adddataForm.loginName" placeholder="登录名" size="mini"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="密码" prop="loginPassword">
          <el-col :span="15">
            <el-input
              v-model="adddataForm.loginPassword"
              show-password
              placeholder="登录密码"
              size="mini"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-col :span="15">
            <el-input v-model="adddataForm.userName" placeholder="用户名称" size="mini"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="角色" prop="roleIdList">
          <el-col :span="15">
            <el-select
              v-model="adddataForm.roleIdList"
              clearable
              placeholder="请选择"
              style="width:100%"
              size="mini"
            >
              <el-option
                v-for="item in rolelist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
          <el-form-item v-if="this.isSysAdmin(adddataForm.userType)" label="所属平台">
          <el-col :span="15" prop="schoolid">
            <el-select
              v-model="adddataForm.schoolid"
              placeholder="请选择"
              style="width:100%"
              size="mini"
               disabled="disabled"
            >
              <el-option
                v-for="item in schooloption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
          <el-form-item v-if="this.isAgent(adddataForm.userType)" label="所属代理商">
          <el-col :span="15" prop="schoolid">
            <el-select
              v-model="adddataForm.schoolid"
              disabled="disabled"
              placeholder="请选择"
              style="width:100%"
              size="mini"
            >
              <el-option
                v-for="item in schooloption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item  v-if="this.isUnitUser(adddataForm.userType)" label="管理的学校">
          <el-col :span="15" prop="schoolid">
            <el-select
              v-model="adddataForm.schoolid"
              clearable
              placeholder="请选择"
              style="width:100%"
              size="mini"
            >
              <el-option
                v-for="item in schooloption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addvisible()">取消</el-button>
        <el-button type="primary" @click="adddataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :before-close="editcloseDialog"
      width="500px"
      center
      title="修改账户"
      :close-on-click-modal="false"
      :visible.sync="editDialogFormVisible"
    >
      <el-form
        :model="eidtdataForm"
        :rules="eidtdataRule"
        ref="eidtdataForm"
        @keyup.enter.native="eidtdataFormSubmit()"
        label-width="80px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-col :span="15">
            <el-input v-model="eidtdataForm.userName" placeholder="用户名称" size="mini"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editvisible()">取消</el-button>
        <el-button type="primary" @click="editataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 重置密码 -->
    <el-dialog
      width="500px"
      center
      title="重置账户密码"
      :before-close="passwordcloseDialog"
      :close-on-click-modal="false"
      :visible.sync="passwordFormVisible"
    >
      <el-form
        :model="passwordForm"
        :rules="passworddataRule"
        ref="passwordForm"
        @keyup.enter.native="passwordFormSubmit()"
        label-width="80px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-col :span="15">
            <el-input
              show-password
              v-model="passwordForm.newPassword"
              placeholder="新密码"
              size="mini"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-col :span="15">
            <el-input
              show-password
              v-model="passwordForm.confirmPassword"
              placeholder="确认密码"
              size="mini"
            ></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordvisible()">取消</el-button>
        <el-button type="primary" @click="passwordataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 分配账户列表 -->
    <el-dialog title="可引入账户" :visible.sync="dialogTableVisible" :close-on-click-modal="false" width="700px">
      <el-table :data="tableData1">
        <el-table-column prop="loginName" label="登录名"></el-table-column>
        <el-table-column prop="userName" label="用户名称" width="200"></el-table-column>
        <el-table-column prop="roleName" label="角色" width="200"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="adduser(scope.row)" size="mini" icon="el-icon-plus">引入</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChangepage1"
          :current-page="currentPage1"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize1"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordCount1"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { JSEncrypt } from "jsencrypt";
export default {
  data() {
    var validateConfirmPassword = (rule, value, callback) => {
      if (this.passwordForm.newPassword !== value) {
        callback(new Error("确认密码与新密码不一致"));
      } else {
        callback();
      }
    };
    return {
      publicKey:
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCx8wyZzYxaffWrJ4jooN554npe5vD2RSQGNXOY5UZz6hcIW0jdEk1KcdclE7mJPiI2DmgUjBp4Lau+bNmZxmLBqFHUMd29mWyqX+LuYVoymxs8f3VJF+7PqZzuKbtSOyXfcyjIIgtB06YlX4SXx4FCErGRx+MDseN2ObHSPme/3wIDAQAB",
      addDialogFormVisible: false,
      editDialogFormVisible: false,
      passwordFormVisible: false,
      rolelist: [],
      schooloption: [],
      userTypeList: [],
      unitNameTip:'',
      adddataForm: {
        loginName: "",
        roleIdList: "",
        loginPassword: "",
        userName: "",
        schoolid: "",
        userType: ""
      },
      eidtdataForm: {
        userName: "",
        roleIdList: ""
      },
      passwordForm: {
        password: "",
        newPassword: "",
        confirmPassword: "",
        userGuid: ""
      },
      adddataRule: {
        loginName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        loginPassword: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "登录名不能为空", trigger: "blur" }
        ],
        roleIdList: [
          { required: true, message: "选择角色", trigger: ["blur", "change"] }
        ],
        userType: [
          {
            required: true,
            message: "选择账户类型",
            trigger: ["blur", "change"]
          }
        ]
      },
      eidtdataRule: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ]
      },
      passworddataRule: {
        password: [
          { required: true, message: "原密码不能为空", trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" }
        ]
      },
      //分配列表信息
      tableData1: [],
      pageSize1: 10,
      pageNum1: 1,
      currentPage1: 1,
      recordCount1: 0,
      searchInfo1: {},
      dialogTableVisible: false
    };
  },
  created() {
    this.unitGuid = this.$store.state.user.changeschoolid;
    this.userType = sessionStorage.getItem("userType");
    this.unitType = this.$store.state.user.unitType;
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid;
      }
    }
  },
  props: ["userGuid", "userName", "row"],
  methods: {
    //获取新增多选数据
    getrole() {
      this.$http({
        url: this.$http.adornUrl("/sys/get-role-select"),
        method: "post",
        data: this.$http.adornData({
          messageContent: this.unitGuid,
          messageType: 0
        })
      }).then(({ data }) => {
        console.log(data);
        if (data.messageCode === 200) {
          let rolelistdata = data.messageContent;
          if (this.rolelist.length == 0) {
            for (var i = 0; i < rolelistdata.length; i++) {
              var itemObj = {
                label: rolelistdata[i].name,
                value: rolelistdata[i].pkRoleId
              };
              this.rolelist.push(itemObj);
            }
          }
          this.addDialogFormVisible = true;
          return;
        } else {
          this.$message.error(data.errorMessage);
          return;
        }
      });
    },
    //获取单位信息
    getschool() {
      this.$http({
        url: this.$http.adornUrl("/unit/unit-brief"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.$store.state.user.changeschoolid, // 当前单位guid
            userGuid: this.userGuid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        // console.log(data)
        // return
        if (data.messageCode === 200) {
          let schooolist = data.messageContent;
          this.schooloption = [];
          this.adddataForm.schoolid = null;
          for (var i = 0; i < schooolist.length; i++) {
            var itemObj = {
              label: schooolist[i].unitName,
              value: schooolist[i].unitGuid
            };
            this.schooloption.push(itemObj);
          }
          this.addDialogFormVisible = true;
          return;
        } else {
          this.$message.error(data.errorMessage);
          return;
        }
      });
    },
    //表单提交
    adddataFormSubmit() {
      this.$refs["adddataForm"].validate(valid => {
        let encryptor = new JSEncrypt();
        encryptor.setPublicKey(this.publicKey);
        let loginpassword = encryptor.encrypt(
          this.$md5(this.adddataForm.loginPassword)
        );
        this.operationId = this.userGuid;
        // role.push(this.adddataForm.roleIdList)
        // return
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/sys/add-system-user"),
            method: "post",
            data: this.$http.adornData({
              messageContent: {
                loginName: this.adddataForm.loginName,
                loginPassword: loginpassword,
                operationGuid: this.userGuid,
                role: this.adddataForm.roleIdList,
                userName: this.adddataForm.userName,
                unitGuid: this.adddataForm.schoolid,
                currentUnitGuid: this.unitGuid,
                userType: this.adddataForm.userType,
              },
              messageType: 0
            })
          }).then(({ data }) => {
            console.log(data);
            if (data.messageCode == 200) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
              this.addDialogFormVisible = false;
              this.init();
            } else {
              this.$message.error(data.errorMessage);
            }
          });
        }
      });
    },
    //修改提交
    editataFormSubmit() {
      this.$refs["eidtdataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/sys/update-system-user"),
            method: "post",
            data: this.$http.adornData({
              messageContent: {
                operationGuid: this.userGuid,
                userName: this.eidtdataForm.userName,
                userGuid: this.eidtdataForm.userGuid
              },
              messageType: 0
            })
          }).then(({ data }) => {
            console.log(data);
            if (data.messageCode == 200) {
              this.$message({
                message: "添加成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
              this.$nextTick(() => {
                this.$refs["eidtdataForm"].resetFields();
              });
              this.editDialogFormVisible = false;
            } else {
              this.$message.error(data.errorMessage);
            }
          });
        }
      });
    },
    //密码重置提交
    passwordataFormSubmit() {
      this.$refs["passwordForm"].validate(valid => {
        if (valid) {
          let encryptor = new JSEncrypt();
          encryptor.setPublicKey(this.publicKey);
          let password = encryptor.encrypt(
            this.$md5(this.passwordForm.password)
          );
          let confirmPassword = encryptor.encrypt(
            this.$md5(this.passwordForm.confirmPassword)
          );
          this.$http({
            url: this.$http.adornUrl("/sys/reset-system-user-pwd"),
            method: "post",
            data: this.$http.adornData({
              messageContent: {
                operationGuid: this.userGuid,
                loginPassword: confirmPassword,
                userGuid: this.passwordForm.userGuid
              },
              messageType: this.messageType
            })
          }).then(({ data }) => {
            if (data.messageCode === 200) {
              this.$message({
                message: "修改密码成功",
                type: "success"
              });
              this.passwordFormVisible = false;
              this.$nextTick(() => {
                this.$refs["passwordForm"].resetFields();
              });
            } else {
              this.$message.error(data.errorMessage);
            }
          });
        }
      });
    },
    //新增初始化
    init() {
      this.$nextTick(() => {
        this.$refs["adddataForm"].resetFields();
      });
    },
    addinit() {
      // 初始化可新增用户类型
      if (this.isSysAdmin(this.userType)) {
        if (this.isSystemUnit(this.unitType)) {
          // 系统管理员在系统单位只能新增系统账户
          this.userTypeList = [{ label: "系统管理员", value: 1 }];
          //this.adddataForm.userType=1;
        } else if (this.isAgentUnit(this.unitType)) {
          // 系统管理员在代理商单位可新增代理商和单位账户
          this.userTypeList = [
            { label: "代理商", value: 50 },
            { label: "单位用户", value: 100 }
          ];
        } else {
          // 系统管理员在学校只能新增单位账户
          this.userTypeList = [{ label: "单位用户", value: 100 }];
         // this.adddataForm.userType=100;
        }
      } else {
        this.userTypeList = [{ label: "单位用户", value: 100 }];
       // this.adddataForm.userType=100;
      }
      this.getrole();
    },
    eidtinit(row) {
      this.editDialogFormVisible = true;
      this.eidtdataForm.userName = row.userName;
      this.eidtdataForm.userGuid = row.userGuid;
      // console.log(row)
    },
    passwordit(row) {
      this.passwordFormVisible = true;
      this.passwordForm.userGuid = row.userGuid;
    },
    //关闭对话框
    closeDialog(done) {
      this.$refs["adddataForm"].resetFields();

      done();
    },
    editcloseDialog(done) {
      this.$refs["eidtdataForm"].resetFields();
      done();
    },
    passwordcloseDialog(done) {
      this.$refs["passwordForm"].resetFields();
      done();
    },
    addvisible() {
      this.addDialogFormVisible = false;
      this.$refs["adddataForm"].resetFields();
    },
    editvisible() {
      this.editDialogFormVisible = false;
      this.$refs["eidtdataForm"].resetFields();
    },
    passwordvisible() {
      this.passwordFormVisible = false;
      this.$refs["passwordForm"].resetFields();
    },
    //分配账户
    //弹窗获取账户信息
    inituserlist() {
      console.log(this.changeschoolid);
      this.searchInfo1.userGuid = this.userGuid;
      this.searchInfo1.unitGuid = this.changeschoolid;
      this.$http({
        url: this.$http.adornUrl("/unit/select-not-manage-unit-page"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum1,
            pageSize: this.pageSize1,
            searchInfo: this.searchInfo1
          },
          messageType: this.messageType
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.tableData1 = data.messageContent.data;
          this.recordCount1 = data.messageContent.recordCount;
          this.currentPage1 = data.messageContent.pageNum;
          this.searchInfo1 = {};
          this.dialogTableVisible = true;
        } else {
          this.$message.error(data.errorMessage);
          this.searchInfo1 = {};
        }
      });
    },
    addinitfenpei() {
      this.$nextTick(() => {
        this.inituserlist();
      });
    },
    adduser(row) {
      this.$http({
        url: this.$http.adornUrl("/unit/distribute-unit-agent"),
        method: "post",
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid,
            userGuid: row.userGuid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          this.$message({
            message: "添加成功",
            type: "success",
            duration: 500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
          this.dialogTableVisible = false;
        } else {
          this.$message.error(data.errorMessage);
        }
      });
    },
    handleSizeChange1(val) {
      this.searchInfo1.userGuid = this.userGuid;
      this.searchInfo1.unitGuid = this.changeschoolid;
      this.pageSize1 = val;
      this.$nextTick(() => {
        this.inituserlist();
      });
    },
    handleCurrentChangepage1(val) {
      this.pageNum1 = val;
      this.searchInfo1.userGuid = this.userGuid;
      this.searchInfo1.unitGuid = this.changeschoolid;
      this.$nextTick(() => {
        this.inituserlist();
      });
    },
    // 用户类型选中事件
    currentSel(selVal) {
      if (this.isSysAdmin(selVal)) {
        // 系统管理员
          // 在代理商单位下创建代理商
          this.schooloption = [
            {
              label: this.$store.state.user.sysUnitName,
              value: this.$store.state.user.sysUnitGuid
            }
          ];
          this.adddataForm.schoolid = this.$store.state.user.sysUnitGuid;
      } else if (this.isAgent(selVal)) {
        // 代理商
        if (this.isAgentUnit(this.unitType)) {
          // 在代理商单位下创建代理商
          this.schooloption = [
            {
              label: this.$store.state.user.agentName,
              value: this.$store.state.user.agentGuid
            }
          ];
          this.adddataForm.schoolid = this.$store.state.user.agentGuid;
        } else {
          this.$message.error("当前不能创建代理商账户，请切换到代理商");
        }
      } else if (this.isUnitUser(selVal)) {
        // 单位用户
        if (this.isOrdinaryUnit(this.unitType)) {
          // 在普通单位下创建单位用户，则只显示当前单位
          this.schooloption = [
            {
              label: this.$store.state.user.schoolName,
              value: this.$store.state.user.schoolGuid
            }
          ];
            this.adddataForm.schoolid = this.$store.state.user.schoolGuid;
        } else if (this.isAgentUnit(this.unitType)) {
          // 在代理商单位下创建普通用户，则返回当前代理商下的所有普通单位
          this.getschool();
        } else {
          this.$message.error("当前不能创建单位用户，请切换到学校");
        }
      } else {
        this.$message.error("账户类型异常");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
ul {
  list-style: none;
}
/deep/.el-scrollbar__wrap {
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-form-item {
  margin-bottom: 10px;
}
.el-dialog--center .el-dialog__body {
  padding-left: 10px;
}
.page {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>